package com.wh1200.mybatis.xmlless.model.component

import com.wh1200.mybatis.xmlless.constant.Strings.LINE_BREAK
import com.wh1200.mybatis.xmlless.constant.WHERE
import com.wh1200.mybatis.xmlless.constant.WHERE_WITHOUT_TRIM
import com.wh1200.mybatis.xmlless.model.base.BaseCriteria
import com.wh1200.mybatis.xmlless.util.trim


/**
 *
 * @author 吴昊
 * @date 2023/12/6 10:23
 * @since v0.0.0
 * @version 1.0
 */
class WhereDeclaration(
    private val whereAppend: String,
    private val groups: List<BaseCriteria>,
    private val defaultWrapWithIf: Boolean
) : ISqlPart() {

  private var sql: String? = null

  override fun toSql(): String {
    if (sql != null) {
      return sql!!
    }
    sql = createSql()
    return sql!!
  }

  private fun createSql(): String {
    val groupBuilders = groups.map {
      it.toSql(defaultWrapWithIf)
    }
    if (groups.isEmpty() && whereAppend.isBlank()) {
      return ""
    }
    val finalExpression = trimCondition(
        groupBuilders.joinToString(LINE_BREAK) + LINE_BREAK + whereAppend
    )
    if (finalExpression.contains("<if ")) {
      return WHERE.format(finalExpression.indent(3))
    }
    return WHERE_WITHOUT_TRIM.format(finalExpression.indent(2))
  }

  private fun trimCondition(sql: String): String {
    return sql.trim().trim(" AND").trim(" OR")
  }

}
